/**
 * 码表设置 - 新建或编辑码表元数据界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0000.CodeTable.CodeTableEditForm", {
  extend: "PSI.AFX.Form.EditForm",

  config: {
    category: null,
    slnCode: "",
    slnName: "",
  },

  /**
   * @override
   */
  initComponent() {
    const me = this;
    const entity = me.getEntity();
    me.adding = entity == null;

    const buttons = [];

    buttons.push({
      text: "保存",
      ...PSI.Const.BTN_STYLE,
      formBind: true,
      iconCls: "PSI-button-ok",
      handler() {
        me._onOK(false);
      },
      scope: me
    }, {
      text: "取消",
      ...PSI.Const.BTN_STYLE,
      handler() {
        const info = entity == null ? "新建码表" : "编辑码表";

        me.confirm(`请确认是否取消：${info}?`, () => {
          me.close();
        });
      },
      scope: me
    });

    const t = entity == null ? "新建码表" : "编辑码表";
    const logoHtml = me.genLogoHtml(entity, t);

    PCL.apply(me, {
      header: {
        title: me.formatTitle(PSI.Const.PROD_NAME),
        height: 40
      },
      width: 650,
      height: 450,
      layout: "border",
      items: [{
        region: "north",
        border: 0,
        height: 50,
        html: logoHtml
      },
      {
        region: "center",
        border: 0,
        layout: "fit",
        items: {
          xtype: "tabpanel",
          id: me.buildId(me, "tabPanel"),
          border: 0,
          bodyStyle: { borderWidth: 0 },
          items: [{
            title: "通用",
            id: "tabGeneral",
            border: 0,
            layout: "fit",
            items: {
              border: 0,
              xtype: "form",
              id: "form1",
              bodyStyle: "margin-top:10px",
              layout: {
                type: "table",
                columns: 2,
                tableAttrs: PSI.Const.TABLE_LAYOUT,
              },
              defaultType: 'textfield',
              fieldDefaults: {
                labelWidth: 90,
                labelAlign: "right",
                labelSeparator: "",
                msgTarget: 'side'
              },
              items: me.getGeneralInputs(),
            }
          }, {
            title: "编辑",
            id: "tabEdit",
            border: 0,
            layout: "fit",
            items: {
              border: 0,
              xtype: "form",
              id: "form2",
              bodyStyle: "margin-top:10px",
              layout: {
                type: "table",
                columns: 2,
                tableAttrs: PSI.Const.TABLE_LAYOUT,
              },
              defaultType: 'textfield',
              fieldDefaults: {
                labelWidth: 95,
                labelAlign: "right",
                labelSeparator: "",
                msgTarget: 'side'
              },
              items: me.getEditInputs(),
            }
          }, {
            title: "业务逻辑",
            id: "tabBiz",
            border: 0,
            layout: "fit",
            items: {
              border: 0,
              xtype: "form",
              id: "form3",
              bodyStyle: "margin-top:10px",
              layout: {
                type: "table",
                columns: 2,
                tableAttrs: PSI.Const.TABLE_LAYOUT,
              },
              defaultType: 'textfield',
              fieldDefaults: {
                labelWidth: 90,
                labelAlign: "right",
                labelSeparator: "",
                msgTarget: 'side'
              },
              items: me.getBizInputs(),
            }
          }, {
            title: "其他",
            id: "tabOther",
            border: 0,
            layout: "fit",
            items: {
              border: 0,
              xtype: "form",
              id: "form4",
              bodyStyle: "margin-top:10px",
              layout: {
                type: "table",
                columns: 2,
                tableAttrs: PSI.Const.TABLE_LAYOUT,
              },
              defaultType: 'textfield',
              fieldDefaults: {
                labelWidth: 60,
                labelAlign: "right",
                labelSeparator: "",
                msgTarget: 'side'
              },
              items: me.getOtherInputs(),
            }
          }],
          listeners: {
            tabchange: {
              fn: me._onTabChange,
              scope: me
            },
          }
        }
      }],
      buttons,
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
        close: {
          fn: me._onWndClose,
          scope: me
        }
      }
    });

    me.callParent(arguments);

    me.editCategoryId = PCL.getCmp(me.buildId(me, "editCategoryId"));
    me.editCategory = PCL.getCmp(me.buildId(me, "editCategory"));
    me.editCode = PCL.getCmp(me.buildId(me, "editCode"));
    me.editName = PCL.getCmp(me.buildId(me, "editName"));
    me.editModuleName = PCL.getCmp(me.buildId(me, "editModuleName"));
    me.editTableName = PCL.getCmp(me.buildId(me, "editTableName"));
    me.editEnableParentId = PCL.getCmp(me.buildId(me, "editEnableParentId"));
    me.editEditColCnt = PCL.getCmp(me.buildId(me, "editEditColCnt"));
    me.editAutoCodeLength = PCL.getCmp(me.buildId(me, "editAutoCodeLength"));
    me.editHandlerClassName = PCL.getCmp(me.buildId(me, "editHandlerClassName"));
    me.editMemo = PCL.getCmp(me.buildId(me, "editMemo"));
    me.editViewPaging = PCL.getCmp(me.buildId(me, "editViewPaging"));
    me.editInputCompany = PCL.getCmp(me.buildId(me, "editInputCompany"));
    me.editModuleDescription = PCL.getCmp(me.buildId(me, "editModuleDescription"));

    // AFX 设置input跳转焦点
    me.__useTabPanel = true;
    me.__tabPanelId = me.buildId(me, "tabPanel");

    inputForm1 = [me.editCategory, me.editCode, me.editName, me.editModuleName];
    if (me.adding) {
      inputForm1.push(me.editTableName);
      inputForm1.push(me.editEnableParentId);
    }
    inputForm1.push(me.editViewPaging, me.editMemo);

    me.__editorList = [
      inputForm1,
      [me.editEditColCnt, me.editAutoCodeLength, me.editInputCompany],
      [me.editHandlerClassName],
      [me.editModuleDescription]
    ];

    const c = me.getCategory();
    if (c) {
      me.editCategory.setIdValue(c.get("id"));
      me.editCategory.setValue(c.get("name"));
    }

    me.form1 = PCL.getCmp("form1");
    me.form2 = PCL.getCmp("form2");
    me.form3 = PCL.getCmp("form3");
    me.form4 = PCL.getCmp("form4");
    me.tabPanelMain = PCL.getCmp(me.buildId(me, "tabPanel"));
  },

  getGeneralInputs() {
    const me = this;

    const width1 = 600;
    const width2 = 300;

    const list = [];

    const entity = me.getEntity();

    list.push({
      xtype: "hidden",
      name: "id",
      value: entity == null ? null : entity.get("id")
    }, {
      id: me.buildId(me, "editCategoryId"),
      xtype: "hidden",
      name: "categoryId"
    }, {
      xtype: "displayfield",
      fieldLabel: "解决方案",
      value: `<span class='PSI-field-note'>${me.getSlnName()}</span>`,
      colspan: 2,
      width: width1,
    }, {
      id: me.buildId(me, "editCategory"),
      xtype: "psi_codetablecategoryfield",
      fieldLabel: "分类",
      allowBlank: false,
      blankText: "没有输入码表分类",
      beforeLabelTextTpl: PSI.Const.REQUIRED,
      valueField: "id",
      displayField: "name",
      slnCode: me.getSlnCode(),
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      },
      width: width2,
    }, {
      id: me.buildId(me, "editCode"),
      fieldLabel: "编码",
      name: "code",
      allowBlank: false,
      blankText: "没有输入码表编码",
      beforeLabelTextTpl: PSI.Const.REQUIRED,
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      },
      width: width2,
    }, {
      id: me.buildId(me, "editName"),
      fieldLabel: "码表名称",
      allowBlank: false,
      blankText: "没有输入中文名称",
      beforeLabelTextTpl: PSI.Const.REQUIRED,
      name: "name",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      },
      width: width2,
    }, {
      id: me.buildId(me, "editModuleName"),
      fieldLabel: "模块名称",
      allowBlank: false,
      blankText: "没有输入模块名称",
      beforeLabelTextTpl: PSI.Const.REQUIRED,
      name: "moduleName",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      },
      width: width2,
    }, {
      id: me.buildId(me, "editTableName"),
      fieldLabel: "数据库表名",
      xtype: me.adding ? "textfield" : "displayfield",
      allowBlank: false,
      blankText: "没有输入数据库表名",
      beforeLabelTextTpl: PSI.Const.REQUIRED,
      name: "tableName",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      },
      colspan: 2,
      width: width1
    }, {
      id: me.buildId(me, "editEnableParentId"),
      fieldLabel: "层级数据",
      xtype: me.adding ? "psi_sysdictfield" : "displayfield",
      beforeLabelTextTpl: PSI.Const.REQUIRED,
      tableName: "t_sysdict_sln0000_ct_tree_view",
      value: "否",
      initIdValue: 0,
      width: width2,
      allowBlank: false,
      blankText: "没有选择是否是层级数据",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      },
    }, {
      id: me.buildId(me, "editViewPaging"),
      xtype: "psi_sysdictfield",
      tableName: "t_sysdict_sln0000_ct_view_paging",
      fieldLabel: "视图分页",
      beforeLabelTextTpl: PSI.Const.REQUIRED,
      allowBlank: false,
      blankText: "没有选择视图是否需要分页",
      value: "不分页",
      initIdValue: 2,
      width: width2,
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      },
    }, {
      id: me.buildId(me, "editMemo"),
      fieldLabel: "备注",
      name: "memo",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      },
      width: width1,
      colspan: 2
    });

    return list;
  },

  getEditInputs() {
    const me = this;

    const width1 = 600;
    const width2 = 300;

    const list = [];

    const entity = me.getEntity();

    list.push({
      id: me.buildId(me, "editEditColCnt"),
      fieldLabel: "编辑布局列数",
      allowBlank: false,
      blankText: "没有输入编辑布局列数",
      beforeLabelTextTpl: PSI.Const.REQUIRED,
      xtype: "numberfield",
      hideTrigger: true,
      allowDecimal: false,
      minValue: 1,
      name: "editColCnt",
      value: entity == null ? 1 : entity.get("editColCnt"),
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      },
      width: width2,
    }, {
      id: me.buildId(me, "editAutoCodeLength"),
      fieldLabel: "自动编码长度",
      allowBlank: false,
      blankText: "没有输入自动编码长度",
      beforeLabelTextTpl: PSI.Const.REQUIRED,
      xtype: "numberfield",
      hideTrigger: true,
      allowDecimal: false,
      minValue: 0,
      maxValue: 20,
      name: "autoCodeLength",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      },
      width: width2,
    }, {
      id: me.buildId(me, "editInputCompany"),
      xtype: "psi_sysdictfield",
      tableName: "t_sysdict_sln0000_ct_input_company",
      fieldLabel: "多公司录入",
      beforeLabelTextTpl: PSI.Const.REQUIRED,
      allowBlank: false,
      blankText: "没有选择码表记录是否需要多公司录入",
      value: "不启用多公司录入",
      initIdValue: 1,
      width: width2,
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      },
      colspan: 2,
    });

    return list;
  },

  getBizInputs() {
    const me = this;

    const width1 = 600;
    const width2 = 300;

    const list = [];

    const entity = me.getEntity();

    list.push({
      id: me.buildId(me, "editHandlerClassName"),
      fieldLabel: "业务逻辑类名",
      name: "handlerClassName",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      },
      width: width1,
      colspan: 2
    });

    return list;
  },

  /**
   * @private
   */
  getOtherInputs() {
    const me = this;

    const width1 = 600;
    const width2 = 300;

    const list = [];

    const entity = me.getEntity();

    list.push({
      id: me.buildId(me, "editModuleDescription"),
      fieldLabel: "模块描述",
      name: "handlerClassName",
      listeners: {
        specialkey: {
          fn: me._onEditLastSpecialKey,
          scope: me
        }
      },
      width: width1,
      colspan: 2
    });

    return list;
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    PCL.get(window).on('beforeunload', me.__onWindowBeforeUnload);

    if (me.adding) {
      // 新建
      me.editTableName.setValue(`t_${me.getSlnCode()}_ct_`.toLocaleLowerCase());

      me.editAutoCodeLength.setValue(0);
    } else {
      // 编辑
      const el = me.getEl();
      el && el.mask(PSI.Const.LOADING);
      me.ajax({
        url: me.URL("SLN0000/CodeTable/codeTableInfo"),
        params: {
          id: me.getEntity().get("id")
        },
        callback(options, success, response) {
          if (success) {
            const data = me.decodeJSON(response.responseText);
            me.editCategory.setIdValue(data.categoryId);
            me.editCategory.setValue(data.categoryName);
            me.editCode.setValue(data.code);
            me.editName.setValue(data.name);
            me.editModuleName.setValue(data.moduleName);
            me.editTableName.setValue(`<span class='PSI-field-note'>${data.tableName}</span>`);
            // 当编辑的时候，me.editEnableParentId是个displayfield
            me.editEnableParentId.setValue(`<span class='PSI-field-note'>${data.enableParentName}</span>`);
            me.editEditColCnt.setValue(data.editColCnt);
            me.editAutoCodeLength.setValue(data.autoCodeLength);
            me.editHandlerClassName.setValue(data.handlerClassName);
            me.editMemo.setValue(data.memo);
            me.editViewPaging.setIdValue(data.viewPaging);
            me.editViewPaging.setValue(data.viewPagingDisplay);
            me.editInputCompany.setIdValue(data.inputCompany);
            me.editInputCompany.setValue(data.inputCompanyDisplay);
            me.editModuleDescription.setValue(data.moduleDescription);
          }

          el && el.unmask();
        }
      });
    }

    me.setFocusAndCursorPosToLast(me.editCode);
  },

  /**
   * @private
   */
  _onOK() {
    const me = this;

    me.editCategoryId.setValue(me.editCategory.getIdValue());

    // 检查数据是否录入完整
    let f = me.form1;
    if (!f.getForm().isValid()) {
      me.showInfo("数据没有录入完整", () => {
        me.tabPanelMain.setActiveTab(0);
      });

      return;
    }

    f = me.form2;
    if (!f.getForm().isValid()) {
      me.showInfo("数据没有录入完整", () => {
        me.tabPanelMain.setActiveTab(1);
      });

      return;
    }

    f = me.form3;
    if (!f.getForm().isValid()) {
      me.showInfo("数据没有录入完整", () => {
        me.tabPanelMain.setActiveTab(2);
      });

      return;
    }

    f = me.form4;
    if (!f.getForm().isValid()) {
      me.showInfo("数据没有录入完整", () => {
        me.tabPanelMain.setActiveTab(3);
      });

      return;
    }

    const entity = me.getEntity();
    const params = {
      id: entity == null ? null : entity.get("id"),
      slnCode: me.getSlnCode(),
      categoryId: me.editCategoryId.getValue(),
      code: me.editCode.getValue(),
      name: me.editName.getValue(),
      moduleName: me.editModuleName.getValue(),
      tableName: me.editTableName.getValue(),
      handlerClassName: me.editHandlerClassName.getValue(),
      memo: me.editMemo.getValue(),
      editColCnt: me.editEditColCnt.getValue(),
      viewPaging: me.editViewPaging.getIdValue(),
      autoCodeLength: "",
      inputCompany: me.editInputCompany.getIdValue(),
      moduleDescription: me.editModuleDescription.getValue(),
    }
    if (!entity) {
      // 这是新建码表的场景
      PCL.apply(params, {
        enableParentId: me.editEnableParentId.getIdValue(),
      });
    }
    const el = me.getEl();
    el?.mask(PSI.Const.SAVING);

    const r = {
      url: me.URL("SLN0000/CodeTable/editCodeTable"),
      params,
      callback(options, success, response) {
        el && el.unmask();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          if (data.success) {
            me.tip("数据保存成功", true);
            me._lastId = data.id;
            me.close();
          } else {
            me.showInfo(data.msg);
          }
        } else {
          el?.unmask();
          me.showInfo(action.result.msg);
        }
      }
    };

    me.ajax(r);
  },

  /**
   * @private
   */
  _onEditLastSpecialKey(field, e) {
    const me = this;

    if (e.getKey() === e.ENTER) {
      me._onOK();
    }
  },

  /**
   * @private
   */
  _onWndClose() {
    const me = this;

    PCL.WindowManager.hideAll();

    PCL.get(window).un('beforeunload', me.__onWindowBeforeUnload);

    if (me._lastId) {
      const parentForm = me.getParentForm();
      parentForm?.refreshMainGrid?.apply(parentForm, [me._lastId]);
    }
  },

  /**
  * TabPanel选中的Tab发生改变的时候的时间处理函数
  * @private
  */
  _onTabChange(tabPanel, newCard, oldCard, eOpts) {
    const me = this;

    const id = newCard.getId();

    // 延迟0.1秒后设置input焦点
    // 这是一个奇怪的写法，不这样处理，就不能正确设置焦点
    // 原因目前不明
    PCL.Function.defer(() => {
      if (id == "tabGeneral") {
        me.setFocusAndCursorPosToLast(me.editCode);
      } else if (id == "tabEdit") {
        me.setFocusAndCursorPosToLast(me.editEditColCnt);
      } else if (id == "tabBiz") {
        me.setFocusAndCursorPosToLast(me.editHandlerClassName);
      } else if (id == "tabOther") {
        me.setFocusAndCursorPosToLast(me.editModuleDescription);
      }
    }, 100);
  },
});
